package 力扣_树算法.树与链表;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zx
 * @create 2022-10-13 20:15
 */
public class 二叉树展开为链表_114 {
    /**
     * 正确解法
     */
    List<TreeNode> list = new ArrayList<>();
    public void flatten(TreeNode root) {
        preOrder(root);
        for (int i = 0; i < list.size() - 1; i++) {
            TreeNode pre = list.get(i);
            TreeNode cur = list.get(i + 1);
            pre.left = null;
            pre.right = cur;
        }
    }
    private void preOrder(TreeNode root){
        if(root == null){
            return;
        }
        list.add(root);
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * @return 当时的笔试题
     */
    public TreeNode treeToLinkedList (TreeNode node) {
        List<TreeNode> list = new ArrayList<>();
        TreeNode dummy = new TreeNode(100000);
        TreeNode temp = dummy.right;
        preOrder(node,list);
        for(TreeNode i : list){
            temp.right = i;
            i.left = null;
            temp = temp.right;
        }
        return dummy.right;
    }
    private void preOrder(TreeNode root, List<TreeNode> list){
        if(root == null){
            return;
        }
        list.add(root);
        preOrder(root.left);
        preOrder(root.right);
    }


    /**
     * 证明当时笔试时的思路是正确的,但是细节出错了
    List<TreeNode> list = new ArrayList<>();
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) return;
        preOrder(root);
        TreeNode temp = list.get(0);
        for (TreeNode i : list) {
            temp.right = i;
            i.left = null;
            temp = temp.right;
        }
    }

    private void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        list.add(root);
        preOrder(root.left);
        preOrder(root.right);
    }
     */
}